package com.cloud.logger.zchain.adapter.http;

import com.cloud.logger.zchain.core.ChainNode;
import com.cloud.logger.zchain.core.IServerRequestAdapter;
import javax.servlet.http.HttpServletRequest;
import static com.cloud.logger.zchain.core.IdConversion.convertToLong;

/**
 * User: wcy
 * Date: 2017/11/20
 * Time: 16:49
 */
public class HttpServerRequestAdapter implements IServerRequestAdapter{

    private final HttpServletRequest request;
    private final NodeNameProvider spanNameProvider;

    public HttpServerRequestAdapter(HttpServletRequest request, NodeNameProvider spanNameProvider) {
        this.request = request;
        this.spanNameProvider = spanNameProvider;
    }

    public ChainNode getChainNode() {
        String parentNodeId = request.getHeader(AdapterHttpHeaders.ParentNodeId.getName());
        String rootId = request.getHeader(AdapterHttpHeaders.RootId.getName());
        String nodeId = request.getHeader(AdapterHttpHeaders.NodeId.getName());

        if (rootId != null && nodeId != null) {
            return getChainNode(rootId, nodeId, parentNodeId);
        }else
            return ChainNode.EMPTY;
    }

    static ChainNode getChainNode(String rootId, String nodeId, String parentNodeId) {
        return ChainNode.builder()
                .rootId(rootId)
                .nodeId(nodeId)
                .parentId(parentNodeId == null ? null : parentNodeId).build();
    }

    public String getChainName() {
        return spanNameProvider.spanName(request);
    }

}
